from google.appengine.ext import db

def prefetch_refprop(entities, prop):
	ref_keys = [prop.get_value_for_datastore(x) for x in entities]
	
	entities_with_null_ref = [x[0] for x in zip(entities, ref_keys) if x[1] is None]
	for entity in entities_with_null_ref:
		prop.__set__(entity, None)
		
	if len(filter(lambda x: x is not None, ref_keys)) > 0:
		filtered_entities, filtered_ref_keys = zip(*[x for x in zip(entities, ref_keys) if x[1] is not None])
		ref_entities = dict((x.key(), x) for x in db.get(set(filtered_ref_keys)))
		for entity, ref_key in zip(filtered_entities, filtered_ref_keys):
			prop.__set__(entity, ref_entities[ref_key])
		
	return entities